﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataRepositoryLayer.Interfaces;
using ModelLayer;
using System.Runtime.Serialization;

namespace DataRepositoryLayer.Classes
{
    public class UserAccountRepository : GenericDataRepository<UserAccount>, IUserAccountRepository
    {
        public UserAccountRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
        {

        }

        public UserAccount CheckSessionToken(string sessionToken)
        {
            if(IsGoodToken(sessionToken))
            {
                return GetSingle(ua => ua.session_token == sessionToken);
            }
            return null;
        }

        public UserAccount CheckEmailToken(string sessionToken)
        {
            if(IsGoodEmailToken(sessionToken))
            {
                return GetSingle(ua => ua.session_token == sessionToken);
            }
            return null;

        }

        private bool IsGoodToken(string sessionToken)
        {
            long ticks = 0;
            if(sessionToken == null || sessionToken.Length < 11 || !Int64.TryParse(sessionToken.Substring(10), out ticks))
            {
                return false;
            }

            DateTime now = DateTime.Now;
            return now.Ticks - ticks < (long) 10000 * 1000 * 60 * 20;
        }

        private bool IsGoodEmailToken(string sessionToken)
        {
            long ticks = 0;
            if (sessionToken == null || !sessionToken.StartsWith("_") || sessionToken.Length < 11 || !Int64.TryParse(sessionToken.Substring(10), out ticks))
            {
                return false;
            }

            DateTime now = DateTime.Now;
            return now.Ticks - ticks < (long)10000 * 1000 * 60 * 60 * 24;
        }


        public UserAccount GetByUsername(string username)
        {
            return GetSingle(ua => ua.username == username);
        }

        public IList<UserAccount> GetForManagementSystem()
        {
            return GetAll(ua => ua.RouteReservations);
        }


        public bool IsUsernameTaken(UserAccount account)
        {
            return context.Accounts.Where(a => a.username == account.username).Count() > 0;
        }
    }
}
